package com.spring.provideronetest.controller;

import com.spring.provideronetest.Utils.RedisUtils;
import com.spring.provideronetest.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @auther zhangxiangtao
 * @date 2021/1/3
 */
@RestController
@RequestMapping("/user")
public class UserController {


	@Autowired
	private UserService userService;
	public static final Logger log = LoggerFactory.getLogger(UserController.class);

//	@Autowired
//	TestService testService;

	@RequestMapping("/userList")
	public String getUserList() throws InterruptedException {

		log.info("线程名"+Thread.currentThread().getName());
		Thread.sleep(10000);
		return "获取成功";

	}

	@RequestMapping("/add")
	public String addUser(@RequestParam String user){

		if(user!=null){



			return "add success";

		}else{

			return "error";

		}

	}

	@Value("${server.port}")
	String port;

	@RequestMapping("/hi")

	public String home(@RequestParam(value ="name", defaultValue ="zhangsan") String name) {
		Map map = new HashMap();
		map.put("1","2");
		return "hi " + name +" ,i am from port:" +port;

	}



	@RequestMapping("getUser/{id}")
	public String GetUser(@PathVariable int id) {
		return userService.Sel(id).toString();
	}



	@Autowired
	private RedisUtils redisUtils;
	@RequestMapping(value = "/hello/{id}")
	public String hello(@PathVariable(value = "id") String id){
		//查询缓存中是否存在
		boolean hasKey = redisUtils.exists(id);
		String str = "";
		if(hasKey){
			//获取缓存
			Object object =  redisUtils.get(id);
			log.info("从缓存获取的数据"+ object);
			str = object.toString();
		}else{
			//从数据库中获取信息
			log.info("从数据库中获取数据");
//			str = testService.test();
			//数据插入缓存（set中的参数含义：key值，user对象，缓存存在时间10（long类型），时间单位）
			redisUtils.set(id,str,10L, TimeUnit.MINUTES);
			log.info("数据插入缓存" + str);
		}
		return str;
	}

}



